package com.hk.websocket;

import com.hk.ChannelPool;
import com.hk.mini.MBUtil;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketServerHandshakerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class WebsocketServerHandler extends SimpleChannelInboundHandler<Object> {


    private static Logger logger = LoggerFactory.getLogger(WebsocketServerHandler.class);

    private WebSocketServerHandshaker socketServerHandshaker;

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        logger.info("websocket建立连接，ip:"+ctx.channel().remoteAddress());

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        logger.info("websocket断开连接,ip："+ctx.channel().remoteAddress());
        ChannelPool.channelGroup.remove(ctx.channel());
    }


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        //传统的HTTP接入,第一次使用http进行握手
        if (msg instanceof FullHttpRequest){
            FullHttpRequest request = (FullHttpRequest) msg;

            handlerHttpRequest(ctx,request);

//            ctx.channel().writeAndFlush(new TextWebSocketFrame("连接成功"));

            //将建立好的连接进行存储
            ChannelPool.channelGroup.add(ctx.channel());
        }
        //webSocket接入
        else if (msg instanceof TextWebSocketFrame){


            TextWebSocketFrame frame = (TextWebSocketFrame) msg;
            String reader = frame.text();
            logger.info("接收到客户端信息:"+reader);


            queryMsg(reader);



        }else {
            logger.info("未知命令");
        }


    }

    private void queryMsg(String reader) {
        int modAddr;
        try {
            modAddr = Integer.parseInt(reader);
        }catch (Exception e){
//            e.printStackTrace();
            modAddr = 1;
        }


        for (ChannelHandlerContext ctx : ChannelPool.miniPool) {

            logger.info("发送查询状态命令");
            ctx.writeAndFlush(Unpooled.copiedBuffer(MBUtil.stringToHex(getStatusCommand(modAddr))));
        }

    }


    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

        cause.printStackTrace();
        logger.error(cause.getMessage());
        ctx.close();

    }


    /**
     * 第一次以http方式握手
     * @param ctx
     * @param request
     */
    private void handlerHttpRequest(ChannelHandlerContext ctx, FullHttpRequest request) throws IOException {

        Properties properties =new Properties();
        InputStream inputStream =
                WebsocketServerHandler.class.getResourceAsStream("/address.properties");
        properties.load(inputStream);
        inputStream.close();

        String wsIp = properties.getProperty("websocket.ip");
        String wsPort =properties.getProperty("websocket.port");

        String webSocketURL = "ws://"+wsIp+":"+wsPort+"/websocket";

        WebSocketServerHandshakerFactory wsFactory = new WebSocketServerHandshakerFactory(
                webSocketURL,
                null,
                false);

        socketServerHandshaker
                = wsFactory.newHandshaker(request);
        if (socketServerHandshaker==null){
            //发送版本错误
            WebSocketServerHandshakerFactory
                    .sendUnsupportedVersionResponse(ctx.channel());
        }else {
            socketServerHandshaker.handshake(ctx.channel(),request);
        }


    }
    private String getStatusCommand(int modAddr) {
        StringBuffer miniCode = new StringBuffer();

        //起始位
        miniCode.append("FEFE");

        //后续长度
        miniCode.append("000F");

        //命令码
        miniCode.append("EA");

        //版本号
        miniCode.append("0202");

        //主机id
        miniCode.append("00000000");


        StringBuffer childCode = new StringBuffer();

        //模块地址
        childCode.append(String.format("%02x", modAddr));

        //功能码
        childCode.append("03");

        //寄存器起始地址
        childCode.append("0000");

        //寄存器个数
        childCode.append("0025");

        //校验码
        childCode.append(MBUtil.getCRC(childCode.toString()));


        miniCode.append(childCode);

        return miniCode.toString();
    }
}
